package yhao.infra.feature.qiniu.oss.core.request;

import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import yhao.infra.common.util.CommonListUtil;
import yhao.infra.feature.qiniu.oss.core.BucketInfo;
import yhao.infra.feature.qiniu.oss.core.QiniuBaseRequest;
import yhao.infra.feature.qiniu.oss.core.response.QiniuBaseResponse;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 批量删除文件
 * @see <a href="https://developer.qiniu.com/kodo/sdk/1239/java#rs-batch-delete">更多明细</a>
 */
public class QiniuBatchDeleteRequest extends QiniuBaseRequest<QiniuBaseResponse> {
    //是否加水印，仅图片有效
    private boolean waterMark;
    //资源路径
    private List<String> urlList;
    //key值表示资源名，与bucket前缀路径无关，注意，若key不为空，则会使用key而无视url参数
    private List<String> keyList;


    public QiniuBatchDeleteRequest(boolean waterMark) {
        this.waterMark = waterMark;
    }

    public boolean isWaterMark() {
        return waterMark;
    }

    public List<String> getUrlList() {
        return urlList;
    }

    public List<String> getKeyList() {
        return keyList;
    }

    /**
     * key值表示资源名，与bucket前缀路径无关<br/>
     * 注意，若key不为空，则会使用key而无视url参数
     */
    public void setKeyList(List<String> keyList) {
        this.keyList = keyList;
    }

    /**
     * 优先使用key参数
     */
    public void setUrlList(List<String> urlList) {
        this.urlList = urlList;
    }

    @Override
    protected QiniuBaseResponse doRequest() {
        BucketInfo bucket = this.isWaterMark()?protectBucket:fileBucket;
        Configuration cfg = new Configuration(bucket.getZone());
        BucketManager bucketManager = new BucketManager(bucket.getAuth(), cfg);
        List<String> keyList = this.getKeyList();
        if(CommonListUtil.isEmpty(keyList)&&CommonListUtil.isNotEmpty(this.getUrlList())){
            keyList = this.getUrlList().stream()
                    .map(s -> s.replace(bucket.getUrl()+"/",""))
                    .collect(Collectors.toList());
        }
        if(CommonListUtil.isEmpty(keyList)){
            throw new RuntimeException("请输入待删除的资源路径");
        }
        try {
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket.getName(), keyList.toArray(new String[]{}));
            return new QiniuBaseResponse(bucketManager.batch(batchOperations));
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            throw new RuntimeException(ex.response.toString());
        }
    }
}
